import axios from 'axios'
import store from '@/store'
import baseURL from '_conf/url'
import router from '@/router/index'

import { setToken, getToken } from '@/libs/util'

// import { Spin } from 'iview'
const addErrorLog = errorInfo => {
  const { statusText, status, request: { responseURL } } = errorInfo
  let info = {
    type: 'ajax',
    code: status,
    mes: statusText,
    url: responseURL
  }
  if (!responseURL.includes('save_error_logger')) store.dispatch('addErrorLog', info)
}

const gotoLogin = () => {
  let url = window.location.host + '/login'
  window.location.href = url
}

class HttpRequest {
  // constructor (baseUrl = baseURL) {
  //   this.baseUrl = baseUrl
  //   this.queue = {}
  // }
  // 构造函数
  constructor () {
    this.options = {
      method: '',
      url: ''
    }
    // 存储请求队列
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: baseURL,
      // timeout: 1000,
      headers: {
        'Content-Type': 'application/json; charset=utf-8',
        'X-URL-PATH': location.pathname
      }
    }
    return config
  }
  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors (instance, url) {
    let token = getToken()
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true

      //* ************* 统一加token start**************
      if (url.indexOf('login') === -1) { // 非登录请求
        config.headers.common['token'] = token
      }
      // else if (url.indexOf('update') !== -1) { // 若url 包含update，提示是否确定修改
      // } else if (url.indexOf('delete') !== -1) { // 若url中 包含delete，提示是否删除

      // }
      //* ************* 统一加token end**************

      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const { data, status } = res
      if (res.data.code === 1440) { // 登录失败
        setToken('') // 清空token
        router.replace({
          name: 'login',
          query: { redirect: router.currentRoute.fullPath }
        })
      }
      return { data, status }
    }, error => {
      this.destroy(url)
      addErrorLog(error.response)
      return Promise.reject(error)
    })
  }

  // 创建axios实例的方法：  时少龙添加
  create () {
    // return axios.create({
    //   baseURL: baseURL,
    //   // timeout: 1000,
    //   headers: {
    //     'Content-Type': 'application/json; charset=utf-8',
    //     'X-URL-PATH': location.pathname
    //   }
    // })
    return axios.create()
  }
  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
